/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, TextInput, Button, ScrollView,Dimensions,ListView,Alert,StatusBar,TouchableHighlight,Image,RefreshControl } from 'react-native';
import Detail from './Detail';

const instructions = Platform.select({
    ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
    android: 'Double tap R on your keyboard to reload,\n' +
        'Shake or press menu button for dev menu',
});
const circleSize = 8;
const circleMargin = 5;
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

type Props = {};
export default class Home extends Component < Props > {
	constructor(props){
		super(props);
		this.state = {
			isRefreshing: false,
			advertisements:[
				{
					url: require('./images/advertisement(0).jpg')
				},
				{
					url: require('./images/advertisement(1).jpg')
				},
				{
					url: require('./images/advertisement(2).jpg')
				}
			],
			currentPage: 0,
			dataSource: ds.cloneWithRows([
				{
					image: require('./images/item.jpg'),
					title: '商品1',
					subTitle: '描述1'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品2',
					subTitle: '描述2'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品3',
					subTitle: '描述3'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品4',
					subTitle: '描述4'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品5',
					subTitle: '描述5'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品6',
					subTitle: '描述6'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品7',
					subTitle: '描述7'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品8',
					subTitle: '描述8'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品9',
					subTitle: '描述9'
				},
				{
					image: require('./images/item.jpg'),
					title: '商品10',
					subTitle: '描述10'
				}
			])
		};
	}
	render() {
			const advertisementCount = this.state.advertisements.length
			const indicatorWidth = circleSize*advertisementCount+circleMargin*advertisementCount*2
			const left = (Dimensions.get('window').width - indicatorWidth)/2
	    return ( 
	    	<View style = { styles.container }>
	    		<StatusBar backgroundColor={'blue'} barStyle={'default'} networkActivitydicatorVisible={true}></StatusBar>
					<View style={styles.searchbar}>
						<TextInput style={styles.input} placeholder="搜索商品"></TextInput>
						<Button style={styles.button} title='搜索' onPress={() => Alert.alert('你单击了搜索按钮',null,null)}></Button>
					</View>
					<View style={styles.advertisement}>
						<ScrollView ref="scrollview" 
							horizontal={true} 
							showHorizontalScrollIndicator={false} 
							padingEnabled={true}
							>
							{this.state.advertisements.map((advertisement,index)=>{
								return (
									<TouchableHighlight key={index} onPress={() => Alert.alert('你单击了轮播图',null,null)}>
										<Image style={styles.advertisementContent} source={advertisement.url}></Image>
									</TouchableHighlight>
								)
							})}
						</ScrollView>
						<View style={[styles.indicator, {left: left}]}>
							{this.state.advertisements.map((advertisement,index) => {
								return (<View
									key={index}
									style={(index === this.state.currentPage) ? styles.circleSelected: styles.circle}>
								</View>)
							})}
						</View>
					</View>
					<View style={styles.products}>
						<ListView
							dataSource={this.state.dataSource}
							renderSeparator={this._renderSeperator}
							renderRow={this._renderRow}
							refreshControl={this._renderRefreshControl()}
						/>
					</View>
	      </View>
	    );
		}
	
    componentDidMount(){
    	this._startTimer();
    }
    componentWillUnmount(){
    	clearInterval(this.interval)
    }
    _startTimer(){
    	this.interval = setInterval(() => {
    		let nextPage = this.state.currentPage + 1;
    		if(nextPage >=3){
    			nextPage = 0;
    		}
    		this.setState({
    			currentPage: nextPage
    		})
    		const offsetX = nextPage*Dimensions.get('window').width
    		this.refs.scrollview.scrollTo({
    			x: offsetX,
    			y: 0,
    			animated: true
    		})
    	}, 2000)
    }
    _renderRow = (rowData, sectionID, rowID) => {
    	console.log(sectionID)
    	console.log(rowID)
    	return (
    		<TouchableHighlight onPress={()=> {
					const {navigator} = this.props;
					if(navigator){
						navigator.push({
							name: 'detail',
							component: Detail,
							params:{
								productTitle: rowData.title
							}
						})
					}
				}}>
	    		<View style={styles.row}>
						<Image source={rowData.image} style={styles.productImage}></Image>
						<View style={styles.productText}>
							<Text style={styles.productTitle}>{rowData.title}</Text>
							<Text style={styles.productSubTitle}>{rowData.subTitle}</Text>
						</View>
	    		</View>
	    	</TouchableHighlight>
    	)
		}
		_renderSeperator(sectionID, rowId, adjacentRowHighlignted){
			console.log(adjacentRowHighlignted)
			return (
				<View key={`${sectionID}-${rowId}`} style={styles.divider}></View>
			)
		}
		_renderRefreshControl(){
			return (
				<RefreshControl
					refreshing={this.state.isRefreshing}
					onRefresh={this._onRefresh}
					tintColor={'#FF0000'}
					title={'正在刷新数据，请稍后...'}
					titleColor={'#0000FF'}>
				</RefreshControl>
			)
		}
		_onRefresh = () =>{
			this.setState({isRefreshing: true});
			setTimeout(()=>{
				const products = Array.from(new Array(10)).map((value,index)=>{
					return{
						image: require('./images/item.jpg'),
						title: '新商品' + index,
						subTitle: '新商品描述' + index
					}
				})
				this.setState({isRefreshing: false, dataSource: ds.cloneWithRows(products)})
			},1000);
		}
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    searchbar: {
        marginTop: Platform.OS === 'ios' ? 20 : 0,
        height: 40,
        flexDirection: 'row'
    },
    input:{
    	flex:1,
    	borderColor:'gray',
			borderWidth: 2,
			borderRadius: 10
    },
    button:{
    	flex:1
    },
    advertisement: {
        height: 180,
        backgroundColor: 'green',
        justifyContent: 'center',
				alignItems: 'center',
				overflow: 'visible' 
	},
	advertisementContent: {
	   width: Dimensions.get('window').width,
		 height: 180,
		 overflow: 'visible' 
	},
	products: {
		flex: 1
	},
	row:{
		height: 60,
		justifyContent: 'center',
		alignItems: 'center'
	},
	indicator:{
		position: 'absolute',
		top: 160,
		flexDirection: 'row'
	},
	circle:{
		width: circleSize,
		height: circleSize,
		backgroundColor: '#CCC',
		borderRadius: circleSize/2,
		opacity:0.5,
		marginHorizontal: circleMargin
	},
	circleSelected:{
		width: circleSize,
		height: circleSize,
		borderRadius: circleSize/2,
		backgroundColor: 'white',
		marginHorizontal: circleMargin
	},
	row:{
		height: 60,
		flexDirection: 'row',
		alignItems: 'center'
	},
	productImage:{
		marginLeft: 10,
		marginRight: 10,
		alignSelf: 'center',
		width: 40,
		height: 40
	},
	productText:{
		flex:1,
		marginTop: 10,
		marginBottom: 10
	},
	productTitle:{
		flex:3,
		fontSize: 16
	},
	productSubTitle:{
		flex:2,
		fontSize: 14,
		color: 'gray'
	},
	divider:{
		height: 1,
		width: Dimensions.get('window').width - 5,
		marginLeft: 5,
		backgroundColor: 'lightgray'
	}
});